package com.green.model.common;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.green.model.uitl.StringUtil;


/**
 * 
 * @author xsq
 * 
 * @since 2012-11-8
 */
public class QueryMap {
	private Map<String, Object> internalMap = new HashMap<String, Object>();

	public boolean isEmpty() {
		return this.internalMap == null || this.internalMap.isEmpty();
	}

	public QueryMap put(String key, Object value) {
		this.internalMap.put(key, value);
		return this;
	}

	public QueryMap checkPut(String key, Object value) {
		if (StringUtil.isEmpty(value)) {
			return this;
		}
		return this.put(key, value);
	}

	/**
	 * 把值转换成list
	 * 
	 * @param key
	 * @param value
	 * @return
	 */
	public QueryMap checkConvertListPut(String key, Object value) {
		if (StringUtil.isEmpty(value)) {
			return this;
		}
		List<Object> list = new ArrayList<Object>();
		list.add(value);
		return this.put(key, list);
	}

	/**
	 * 把值转换成list
	 * 
	 * @param key
	 * @param value
	 * @return
	 */
	public QueryMap checkConvertListPut(String key, Collection<? extends Object> c, boolean isReplaceSpecialChar) {
		if (c == null || c.isEmpty()) {
			return this;
		}
		List<Object> list = new ArrayList<Object>();

		for (Object object : c) {
			if (object != null) {
				object = isReplaceSpecialChar ? replaceSpecialChar(object) : object;
				list.add(object);
			}
		}
		if (list.size() > 0) {
			return this.put(key, list);
		}
		return this;
	}

	public static String replaceSpecialChar(Object source) {
		if (source == null) {
			return null;
		}
		String value = String.valueOf(source);
		if (StringUtils.isBlank(value)) {
			return "";
		}
		return value.replaceAll("(\\+|~|\\(|\\))", "\\\\$1");
	}

	public void clear() {
		this.internalMap.clear();
	}

	public Map<String, Object> getInternalMap() {
		return this.internalMap;
	}

	public Object getValue(String key, Object defaultValue) {
		if (this.internalMap.containsKey(key)) {
			return this.internalMap.get(key);
		}
		return defaultValue;
	}

	public Object getValue(String key) {
		return this.getValue(key, null);
	}

	public QueryMap put(String key, Object value, String defaultValue) {
		Object v=value;
		if (StringUtil.isEmpty(value)) {
			v = defaultValue;
		}
		return this.put(key, v);
	}
	
	public  static final String getQueryIn(List<String> list)
	{
		if(list == null || list.isEmpty())
		{
			return null;
		}
		StringBuilder sb=new StringBuilder();
        for (String string : list) {
			if(string==null){
				continue;
			}
			string=string.replaceAll("\'", "\"");
            sb.append(",\'").append(string).append("\'");
        }
        return sb.length()>0?sb.toString().substring(1):null;
	}
}
